<template>
  <div class="announcement-edit">
    <div class="header">
      <h2>编辑公告</h2>
    </div>

    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="announcement-form"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入公告标题" />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="6"
          placeholder="请输入公告内容"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          保存
        </el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getDetail, update } from '@/api/announcement'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const formRef = ref(null)

const form = ref({
  title: '',
  content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2到100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
  ]
}

const loadData = async () => {
  try {
    loading.value = true
    const res = await getDetail(route.params.id)
    if (res.code === 200) {
      form.value = res.data
    }
  } catch (error) {
    console.error('加载公告详情失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const res = await update(route.params.id, form.value)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      router.push('/admin/announcement')
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存公告失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  router.push('/admin/announcement')
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.announcement-edit {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  
  .header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
      color: #000;
    }
  }
  
  .announcement-form {
    max-width: 800px;
    
    .el-button {
      margin-right: 10px;
    }
  }
}
</style> 